import os
from PIL import ImageGrab
import pyautogui
from cnocr import CnOcr

from AtomClicker.config.config import CNOCR_MODEL_PATH
from AtomClicker.config.config import ICON_DIR
from AtomClicker.app.atomic_actions import wait_for_image

import time


def click(img):
    # 根据输入的是文字还是path路径来执行不同的函数
    img_path = os.path.join(ICON_DIR, f'{img}')
    if os.path.isfile(img_path):  # 判断是否为文件路径
        click_icon(img)
    else:  # 否则视为文字
        find_and_click_text(img)

    time.sleep(3)


# 点击图标
def click_icon(img):
    img_path = os.path.join(ICON_DIR, f'{img}')
    location = wait_for_image(img_path)
    x = location[0] + 0.5 * location[2]
    y = location[1] + 0.5 * location[3]
    pyautogui.click(x, y)
    # print("click:", img)


def find_and_click_text(target_text):
    # 截取屏幕图像
    screenshot = ImageGrab.grab()

    # 初始化CnOCR对象
    ocr = CnOcr(
        rec_root=os.path.join(CNOCR_MODEL_PATH, 'cnocr'),
        det_root=os.path.join(CNOCR_MODEL_PATH, 'cnstd'),
    )
    # 使用CnOCR进行文字识别
    res = ocr.ocr(screenshot)

    # 检查目标文字是否在屏幕文字中
    for line in res:
        if target_text in line['text']:
            # 获取目标文字的位置
            x1, y1 = line['position'][0]
            x2, y2 = line['position'][2]
            x = (x1 + x2) / 2
            y = (y1 + y2) / 2

            # 移动鼠标到目标位置并点击
            pyautogui.click(x, y)
            print(f"点击了文字：{target_text}")
            return
    print(f"未找到目标文字:{target_text}")
